<?php
/**
 * Create a new Expense main view.
 * 
 * @author Xavier VILAIN
 */
use Fox\Html\Button;
use Fox\Document;
use Fox\Generator;
use Fox\Html\Header\Image;
use Hive\Expense;
use Fox\Html\Screen;

$xview = Xview::instance();

$screen = new Screen('sHeader','create');
$screen->mainTitle(new Image("expenses",MSG(Expense::MSGCL,5)));
// Step 1 - Header
$step1 = Xview::instance()->component("expenses","header");
$screen->add($step1);
// Step 2 - Reference
$step2 = Xview::instance()->component("expenses","reference");
$screen->add($step2);
// Step 3 - Detail
$step3 = Xview::instance()->component("expenses","detail");
$screen->add($step3);
// Step 4 - File
$step4 = Xview::instance()->component("expenses","files");
$screen->add($step4);
// Add Other Action button
$screen->add(new Button("add",null,Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_CREATE_ADD_NEW)));
$screen->add(new Button("cancel",Generator::redirect(Generator::url("expenses",null))));

if($screen->submitted())
{
	$fields = $screen->get();
	var_dump($fields);
	// Check If Period is still open
	if(!$screen->errors())
	{
		// Check if Period is still open
	}

	if(!$screen->errors())
	{
		
		try {
			$fields['idusr'] = User::current()->getId();
			$expenses = new Expense();
			$expenses->setFields($fields);
			// Attach File to the expense
			if(!empty($fields['filename']))
			{
				$fileName = Xview::moveFileToServer();
			
				$data['filename'] = $fileName['filename'];
				$data['destination'] = _TEMP_;
				$data['physicalname'] = $fileName['physicalname'];
				$document = new Document();
				$document->setFields($data);
				$expenses->attach($document);
			}
			$expenses->create();
			$id = $expenses->expenseid;
			Fox\Message::Success(Msg(Expense::MSGCL,15,$id));
			// Depending on the selecting action
			if($screen->buttons("add")->pushed())
			{
				$screen->redirect();
			}
			else
			{
				$xview->redirect("?mod=expenses");
			}
			
		}
		catch (Fox\Object\Exception\Save $e)
		{
			var_dump($e);
			Fox\Message::Error($e->getMessage());
		}
		catch (Exception $e)
		{
			var_dump($e);
			Fox\Message::Error($e->getMessage());
		}
	}
}
echo $screen->display();